package org.tagging.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.tagging.component.security.LoginSuccessHandler;
import org.tagging.exception.LoginWrongPlaceException;
import org.tagging.exception.UsernameAlreadyExistException;
import org.tagging.model.TaggingUser;
import org.tagging.service.impl.other.ClientUserServiceImpl;
import org.tagging.service.impl.other.EmailServiceImpl;
import org.tagging.utils.Asserts;
import org.tagging.utils.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/api/tagging/user")
@Api(value = "注册(PS:登录接口详见主页)", tags = {"用户相关"})
public class ClientUserController {
    @Autowired
    private ClientUserServiceImpl userService;

    @Autowired
    private EmailServiceImpl emailService;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @PostMapping("/login")
    @ApiOperation(value = "普通用户的登陆")
    public void login(@RequestParam("username") String username, @RequestParam("password") String password,
                      HttpServletRequest request, HttpServletResponse response) throws ServletException, LoginWrongPlaceException, IOException {
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
        //此方法会调用登陆逻辑，若用户名或密码错误也会抛出错误
        SecurityContextHolder.clearContext();
        request.login(username, password);
        TaggingUser user = userService.queryByUsername(username, TaggingUser.Column.id, TaggingUser.Column.role);
        Asserts.isUser(user.getRole(), "用户名登录错地方!");
        loginSuccessHandler.onAuthenticationSuccess(request, response, SecurityContextHolder.getContext().getAuthentication());
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册以及修改密码")
    @ApiResponses(
            {@ApiResponse(code = -1, message = "用户名重复"),
                    @ApiResponse(code = 200, message = "注册成功！")}
    )
    public Object register(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("code") String code) throws UsernameAlreadyExistException {
        String codeInSystem = emailService.get(username);
        if (codeInSystem == null || !codeInSystem.equals(code)) {
            return ResponseUtils.build(HttpStatus.BAD_REQUEST.value(), "验证码错误！");
        }
//        emailService.remove(username);
        try {
            int i = userService.addClientUser(username, password);
            emailService.remove(username);
            return ResponseUtils.build(HttpStatus.OK.value(), "注册成功！");
            //若用户名重复，说明为修改密码
        } catch (UsernameAlreadyExistException e) {
            if (emailService.check(username, code)) {
                userService.resetPassword(username, password);
                return ResponseUtils.build(HttpStatus.OK.value(), "重置密码成功！");
            }
            return ResponseUtils.build(HttpStatus.OK.value(), "验证码错误！");
        }
    }

    @GetMapping("/currentUser")
    @PreAuthorize("hasAnyRole('USER','ADMIN')")
    @ApiOperation(value = "获取当前用户标注的信息", notes = "所需权限（登录即可）{\n" +
            "  \"id\": 4,\n" +
            "  \"username\": null,\n" +
            "  \"password\": null,\n" +
            "  \"lastLoginTime\": 上次登陆时间,\n" +
            "  \"role\": 2,\n" +
            "  \"indonesiaCompleteToday\": 0,//今日标注印尼语的数量\n" +
            "  \"indonesiaTotal\": 0,//总共标注印尼语的数量\n" +
            "  \"malayCompleteToday\": 0,//今日标注马来语的数量\n" +
            "  \"malayTotal\": 0//总共标注马来语的数量\n" +
            "}")
    public Object currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        TaggingUser user = userService.queryByUsername(username, TaggingUser.Column.id,
                TaggingUser.Column.indonesiaCompleteToday,
                TaggingUser.Column.indonesiaTotal,
                TaggingUser.Column.malayCompleteToday,
                TaggingUser.Column.malayTotal,
                TaggingUser.Column.role,
                TaggingUser.Column.lastLoginTime);
        return ResponseUtils.build(HttpStatus.OK.value(), "获取用户信息成功！", user);
//        return user;
    }

    @PostMapping("/emailCode")
    @ApiOperation(value = "注册时邮箱验证码获取")
    public Object emailCode(@RequestParam("username") String username) {
        emailService.sendCode(username, "邮箱验证码", "邮箱验证码是：%s（三分钟内有效）");
        return ResponseUtils.build(HttpStatus.OK.value(), "获取邮箱验证码成功");
    }


//    @PostMapping("/forgetPassword")
//    @ApiOperation(value = "修改密码时时邮箱验证码获取")
//    public Object forgetPassword(@RequestParam("username") String username) {
//        emailService.sendCode(username, "忘记密码", "邮箱验证码是：%s（三分钟内有效）");
//        return ResponseUtils.build(HttpStatus.OK.value(), "获取邮箱验证码成功");
//    }

//    @PostMapping("/resetPasswordCode")
//    @ApiOperation(value = "重置密码")
//    public Object resetPassword(@RequestParam("username") String username,
//                                @RequestParam("newPassword") String newPassword,
//                                @RequestParam("code") String code) {
//
//    }

    //    @GetMapping("/showAliveUsers")
//    public Object showAliveUsers() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        return ResponseUtils.build(HttpStatus.OK.value(), "获取所有登录用户的信息成功！");
//    }


}
